<template>
	<div class="exercises-test" v-loading.fullscreen.lock="loading"
		element-loading-text="拼命加载中">
        <el-row class="preview-head" type="flex" align="middle">
            <el-col :span="2" :offset="1">
                <el-button type="text" @click="goBack()"><i class="el-icon-arrow-left"></i>返回</el-button>
            </el-col>
        </el-row>

		<div class="preview-conten maxW">
			
			<div class="preview-conten-l">
				
				<div class="preview-conten-l-h">
					<h3>{{testObj.name}}</h3>
					<p>考试时间：{{totalTime ? totalTime : '--'}} 分钟，满分 {{testObj.score}} 分</p>
				</div>
				<div class="exercises-test-type">
					<a :href="'#'+item.id" v-for="item of questionList">{{item.name}}</a>
					<el-radio-group v-model="type" v-if="0">
						<template v-for="item of questionList">
							<el-radio :label="item.id">{{item.name}}</el-radio>
						</template>
					</el-radio-group>
				</div>

				<ul>
					<template v-for="(type, list) of testList.question_type" >
						<li :id="type.id" class="preview-conten-list" :key="list">

							<!-- <div class="preview-conten-title" v-if="type.id == 1">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，只有一个符合题意的正确答案。错选，不选均不得分。)
							</div>

							<div class="preview-conten-title"  v-else-if="type.id == 2">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，有两个或两个以上符合题意的正确答案。多选、少选、错选、不选均不得分。)
							</div>

							<div class="preview-conten-title"  v-else-if="type.id == 9">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，两个答案中只有一个符合题意的正确答案。)
							</div>
							<div class="preview-conten-title"  v-else>
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，点击文本框，直接在文本框内作答即可。)
							</div> -->
							<div class="preview-conten-title" >
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，共{{type.score}}分<span v-show="type.common">，{{type.common}}。</span>)
							</div>

							<ul class="preview-conten-subject">

								<template v-for="(item, index) of testList.question_list" v-if="parseInt(item.qt_id) == parseInt(type.id)">

									<li :id="'test'+item.id" class="preview-conten-subject-c"  v-if="parseInt(item.type_base_id) === 1"  :key="index">
										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong v-if="item.score">({{item.score}}分)</strong>
											</div>
										</template>


										<el-radio-group v-model="answerList[index].answer[0]"  @change="selectAnswerChange($event, index, item, '1', 1)">
											<ul class="preview-topic">
												<template v-for="(option,key) in item.option">
													
													<li class="preview-subject-title" v-if="item.pattern === 1">
														<el-radio :label="option.name"></el-radio>
														<div class="" v-html="option.value"></div>
													</li>

													<li class="preview-subject-title option-pattern" v-if="item.pattern === 2">
														<el-radio :label="option.name"></el-radio>
														<!-- <el-radio :label="option.name" @change="selectAnswerChange($event, list, index, key , item.id, option.name, 1)"></el-radio> -->
														<!-- <div class="" v-html="option.value"></div> -->
													</li>
												</template>
												
											</ul>
										</el-radio-group>

										<el-collapse accordion class="preview-answer" v-if='0'>
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span v-if="item.keynote == 1">重点程度： 低</span>
														<span v-if="item.keynote == 2">重点程度： 中</span>
														<span v-if="item.keynote == 3">重点程度： 高</span>
													</div>
													
												</template>


												<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>

									<li :id="'test'+item.id" class="preview-conten-subject-c"  v-else-if=" parseInt(item.type_base_id) === 2" :key="index">
										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong v-if="item.score">({{item.score}}分)</strong>
											</div>
										</template>

										<ul class="preview-topic">

											<template  v-for="(option,key) in item.option">
												<li class="preview-subject-title" v-if="item.pattern === 1">
													<el-checkbox  v-model="answerList[index].answer"
													@change="selectAnswerChange($event, index, item, option.name, 2)" 
													:label="option.name"></el-checkbox>
													<div class="" v-html="option.value"></div>
												</li>

												<li class="preview-subject-title option-pattern" v-if="item.pattern === 2">
													<el-checkbox  v-model="answerList[index].answer"
													@change="selectAnswerChange($event,  index, item, option.name, 2)" 
													:label="option.name"></el-checkbox>
													<!-- <div class="" v-html="option.value"></div> -->
												</li>
											</template>
											
										</ul>
										
										<transition name="el-fade-in-linear">
											<div class="preview-next" v-show="item.next">
												<el-button type="primary" @click.prevent="Tocontone(item, index)">下一题</el-button>
											</div>
										</transition>
										
										<el-collapse accordion class="preview-answer" v-if='0'>
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span v-if="item.keynote == 1">重点程度： 低</span>
														<span v-if="item.keynote == 2">重点程度： 中</span>
														<span v-if="item.keynote == 3">重点程度： 高</span>
													</div>
													
												</template>


												<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>

									<li :id="'test'+item.id" class="preview-conten-subject-c"  v-else-if="parseInt(item.type_base_id) === 4"  :key="index">
										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong v-if="item.score">({{item.score}}分)</strong>
											</div>
										</template>


										<el-radio-group v-model="answerList[index].answer[0]" @change="selectAnswerChange($event,  index, item, '9', 9)">
											<ul class="preview-topic">
												<template v-for="(option,key) in item.option">
													
													<li class="preview-subject-title" v-if="item.pattern === 1">
														<el-radio :label="option.name"></el-radio>
														<!-- <div class="" v-html="option.value"></div> -->
													</li>

													<li class="preview-subject-title option-pattern" v-if="item.pattern === 2">
														<el-radio :label="option.name"></el-radio>
														<!-- <div class="" v-html="option.value"></div> -->
													</li>
												</template>
												
											</ul>
										</el-radio-group>

										<el-collapse accordion class="preview-answer" v-if='0'>
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span v-if="item.keynote == 1">重点程度： 低</span>
														<span v-if="item.keynote == 2">重点程度： 中</span>
														<span v-if="item.keynote == 3">重点程度： 高</span>
													</div>
													
												</template>


												<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>

									<li :id="'test'+item.id" class="preview-conten-subject-c"   v-else-if="parseInt(item.type_base_id) === 3"  :key="index">

										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong v-if="item.score">({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
										</template>
										
										<div class="knowledge-answer">
											<span>答案</span>
											<div class="knowledge-">
												<template v-for="num of answerList[index].answer">

											
													 <el-input type="textarea" 
													   :autosize="{ minRows: 1, maxRows: 6}"  resize='none' placeholder="请输入内容, 300个字符内"
													  v-model.trim.native="num.answer" maxlength="300"
													   @input="selectAnswerChange($event,  index,  item, num.answer, 3)">
													 </el-input>
												</template>

											</div>
										</div>

										<transition name="el-fade-in-linear">
											<div class="preview-next" v-show="item.next">
												<el-button type="primary"  @click.prevent="Tocontone(item, index)">下一题</el-button>
											</div>
										</transition>

										<el-collapse accordion class="preview-answer" v-if='0'>
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span v-if="item.keynote == 1">重点程度： 低</span>
														<span v-if="item.keynote == 2">重点程度： 中</span>
														<span v-if="item.keynote == 3">重点程度： 高</span>
													</div>
													
												</template>
												<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>

									<li :id="'test'+item.id" class="preview-conten-subject-c"  v-else  :key="index">

										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong v-if="item.score">({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
										</template>
										
										<div class="knowledge-answer">
											<span>答案</span>
											<div class="knowledge-">

												<vue-ueditor-wrap :config="config1"   :destroy="true"  v-model="answerList[index].answer" class="Ueditor-txt" @input="selectAnswerChange($event, index, item, '0', 0)"></vue-ueditor-wrap>

												
											</div>
										</div>

										<transition name="el-fade-in-linear">
											<div class="preview-next" v-show="item.next">
												<el-button type="primary"  @click.prevent="Tocontone(item, index)">下一题</el-button>
											</div>
										</transition>

										<el-collapse accordion class="preview-answer" v-if='0'>
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span v-if="item.keynote == 1">重点程度： 低</span>
														<span v-if="item.keynote == 2">重点程度： 中</span>
														<span v-if="item.keynote == 3">重点程度： 高</span>
													</div>
													
												</template>
												<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>
								</template>

							</ul>
						</li>
					</template>
				</ul>
			</div>

			<div class="exercises-conten-r" >

				<div class="exercises-conten-time">
					<div class="exercises-time-countdown">
						<i class="el-icon-time"></i>
						<strong>剩余时间</strong>
						<span>{{testObj.time?testObj.time: '00:00:00'}}</span>
					</div>
					<div class="exercises-next-question" >
						<span>自动下一题</span>
						<span>
							<el-switch @change="switchNext"
							  v-model="switchValue"
							  active-color="#13ce66"
							  inactive-color="#ff4949">
							</el-switch>
						</span>
					</div>
				</div>

				<ul class="exercises-conten-r-type">

					<template  v-for="(type, list) of questionList" >
						<li class="exercises-conten-r-type-state">
							<div>{{type.name}}<i>（共{{type.score}}分）</i></div>
							<ul>
								<template  v-for="(item, index) of type.children">
									<li  v-if="parseInt(item.qt_id) == parseInt(type.id)" :key="index" @click="setCheck(item)">
										<input type="checkbox" :name="index" :checked="item.html_default">
										<a :href="'#test'+item.id">{{++index}}</a>
									</li>
								</template>
							</ul>
						</li>
					</template>
						
				</ul>

				<div class="exercises-answer-state">
					<span>已答<i></i></span>
					<span>未答<i></i></span>
				</div>

				
				<div class="exercises-conten-r-btn">
					<el-button type="primary" @click.prevent="setSubmit(1)">交卷</el-button>
				</div>

			</div>
		</div>

		<!-- 预览图片 -->
		<image-viewer 
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
	


	</div>
</template>

<script>
	// import { VueEditor } from "vue2-editor";


	// import Ueditor from '@/components/common/Ueditor.vue';
	import VueUeditorWrap from 'vue-ueditor-wrap' // ES6 Module
	export default {
		components: {VueUeditorWrap},
		data(){
			return {
				imagePreview: {/*图片预览*/
					showViewer: false,
					previewSrcList: []
				},
				offsetTop: 0,
				offsetRigth: 0,
				tasksVisible: false,
				headClassList: null,
				type: 1,
				switchValue: false,

				blankNumArr:[],
	
				testList:[],		/* 试卷列表 */
				answerList: [],		/* 试卷答案 */
				testObj: {
					name: '',
					time: '',
					time2: '',
					score: 0,
					type: 1,
				},
				totalTime: 0,			/*考试时间*/
				answerStatus: 0,	/*0.未作答，1.已作答*/
				recordId: '',		/*试卷id*/
				questionList: [], 	/*试卷列表*/
				answerList: [],		/*答案数组*/
				unlimited:'', /*1不限时  0限时*/

				

				customToolbar: [
					[{ list: "ordered" }, { list: "bullet" }],
					[{ 'color': [] }, { 'background': [] }], 
					['clean']
				],
				Usedtimer:  '',
				loading: true,
				imgIndex: 0,
				timer: null,

		        config1: {
		        	zIndex: 3,
		        	textIndent: 0,
		        	maximumWords: 2000,
		        	elementPathEnabled: false,/*元素路径*/
		        	enableAutoSave: false,
					autoHeightEnabled: false,
					autoFloatEnabled: false,//不允许滚动时固定在顶部
					initialContent:'请输入内容...',   //初始化编辑器的内容,也可以通过textarea/script给值，看官网例子
					autoClearinitialContent:true, //是否自动清除编辑器初始内容，注意：如果focus属性设置为true,这个也为真，那么编辑器一上来就会触发导致初始化的内容看不到了
					initialFrameWidth: null,
					initialFrameHeight: 150,
					serverUrl: this.BASE_URL+"/static/_/UEditor/1.4.3//php/controller.php?action=uploadimage",
					BaseUrl: this.BASE_URL,
					// UEDITOR_HOME_URL: process.env.BASE_URL+'ueditor/',
					UEDITOR_HOME_URL: process.env.BASE_URL ? process.env.BASE_URL + 'ueditor/' : '/static/ueditor/',
					toolbars: [
						['bold', 'italic', 'underline',  'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'pasteplain',  'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc','fullscreen',  'simpleupload','link', 'justifyleft', 'justifyright', 'justifycenter', 'lineheight', 'fontfamily', 'fontsize', 'undo', 'redo']
					]
		        },

			}
		},
		watch: {
		
		},

		mounted(){
			this.headClassList = document.querySelector('#trunk').classList;
			this.headClassList.add('hidden-header')

			document.querySelector('.preview-conten-l').addEventListener('click',  (e)=> {
				
				let [targetSrc ,imgs, srcArr, currentIdx] = ['', '', '', '']
				if (e.target.nodeName === 'IMG') {

					this.imagePreview.showViewer = true
					targetSrc = e.target.src;
					imgs = [...e.target.parentNode.children];
					srcArr = imgs.map(item=>item.currentSrc);
					currentIdx = srcArr.indexOf(targetSrc);

					this.imagePreview.previewSrcList = srcArr
					this.imgIndex = targetSrc

				}
			
			}, false)

			this.$nextTick(()=>{
				this.getTestList()
			})

			/*this.listenResize()
			window.addEventListener('resize',this.listenResize);*/
			

		},
		computed: {
			imageIndex() {
			    return this.imagePreview.previewSrcList.indexOf(this.imgIndex);
			}

		},
		destroyed(){
			this.headClassList.remove('hidden-header')
		},
		created(){
			
		},
		methods: {
			/**
			 * 关闭图片
			 * @DateTime 2020-04-16T17:40:41+0800
			 * @qiu_m
			 * @return   {[type]}                 [description]
			 */
			 closeViewer() {
			 	this.imagePreview.showViewer = false;
			 	this.imagePreview.previewSrcList = []
			 },
			/**
			 * 根据 id 滑动到相应的数据头部
			 * @qiu_m
			 * @DateTime 2019-12-10T09:55:55+0800
			 * @param    {[type]}                 obj   [description]
			 * @param    {[type]}                 index [description]
			 */
			Tocontone(obj, index){

				let [elment, anchor, cont] = ['', '', '']

				for (let i = 0; i < this.answerList.length; i++) {
					/*判断选择的索引大于数据列表的索引进行判断*/
					if (i > index) {
						/*填空题是多个答案，进行遍历判断是否有填写答案（不含全部答案）*/
						if (this.answerList[i].type == 3) {

							let flas = false
							for (let j = 0; j < this.answerList[i].answer.length; j++) {

								if (this.answerList[i].answer[j].answer != '') {
									flas= true
								}
							}

							if (flas) {
								// console.log(this.answerList[i].answer, this.answerList[i].id, i, 3, anchor.offsetTop)
								continue
							}else{
								elment = '#test'+(this.answerList[i].id)
								anchor = document.querySelector(elment)
								cont = anchor.querySelector('.preview-conten-subject-t').offsetHeight;
								// console.log(this.answerList[i].answer, this.answerList[i].id, i, 4, anchor.offsetTop)
								break
							}
							

						}else{

							/*答案不为空就跳过该数据*/
							if (this.answerList[i].answer.length != 0 || this.answerList[i].answer != '') {
								// console.log(this.answerList[i].id, i,1)
								continue
							}else{/*判断答案为空时，获取该数据id进行赋值改变滚动条*/
								elment = '#test'+(this.answerList[i].id)
								anchor = document.querySelector(elment)
								cont = anchor.querySelector('.preview-conten-subject-t').offsetHeight;
								// console.log(this.answerList[i].answer, this.answerList[i].id, i, 2)
								break
							}
						}
					}
					
				}
				this.$nextTick(() => {
					document.documentElement.scrollTop = (anchor.offsetTop) - 10;
				})


			},
			/**
			 * 开启自动下一题
			 * @qiu_m
			 * @DateTime 2019-12-09T14:52:16+0800
			 * @param    {[type]}                 val [description]
			 * @return   {[type]}                     [description]
			 */
			switchNext(val){
				if (val) {
					this.testList.question_list.forEach(item=>{
						item.next = val
					})
				}else{
					this.testList.question_list.forEach(item=>{
						item.next = val
					})
				}
			},

			listenResize(){
				let left = document.querySelector('.preview-conten-l')
				this.offsetTop = left.offsetTop
				this.offsetRigth = (left.offsetLeft + left.offsetWidth) + 20 
			},
			/**
			 * 试卷倒计时
			 * @DateTime 2019-08-22T15:03:42+0800
			 * @param    {[type]}                 timestamp [description]
			 * @return   {[type]}                           [description]
			 */
			countdowm(timestamp){
        		let self = this;
        		let t = parseInt(timestamp * 1000)
        		let timeLong2 = parseInt(this.testObj.time * 1000)
        		this.testObj.time = '00:00:00';
        		this.Usedtimer = setInterval( ()=>{

        			
        			if(t > 0){
        				t -=  1000
        				timeLong2 -= 1000;

        				let day = Math.floor(t / 86400000);
        				let hour=Math.floor((t / 3600000) % 24);
        				let min=Math.floor((t / 60000) % 60);
        				let sec=Math.floor((t / 1000) % 60);
        				hour = hour < 10 ? "0" + hour : hour;
        				min = min < 10 ? "0" + min : min;
        				sec = sec < 10 ? "0" + sec : sec;
        				let format = '';
        				if(day > 0){
        					format = `${day}:${hour}:${min}:${sec}`;
        				} 
        				if(day <= 0 && hour > 0 ){
        					format = `${hour}:${min}:${sec}`; 
        				}
        				if(day <= 0 && hour <= 0){
        					format =`${hour}:${min}:${sec}`;
        				}
        				this.testObj.time = format;
        			}

        			if(timeLong2 <= 0 ){
        				 clearInterval(this.Usedtimer);
        				 timeLong2 = 0
        				 t = 0
        				this.setSubmit(0)
        			}

        		},1000);
        	},
			/**
			 * 编辑器初始化
			 * @return {[type]} [description]
			 */
			editorInit() {
			  //修改输入框内文字与边界的宽
			  // let test = document
			  //   .getElementById("d1_ifr")
			  //   .contentWindow.document.getElementById("tinymce");
			  // 	test.style.margin = "8px 25px";
			},
			/**
			 * 选择的答案
			 * @DateTime 2019-08-22T10:14:19+0800
			 * @param    {[stong]}       selected    [选中的答案]
			 * @param    {[stong]}       list        [题型的索引]
			 * @param    {[stong]}       index       [试题的索引]
			 * @param    {[stong]}       key         [选择题的索引]
			 * @param    {[stong]}       id          [试题的 id]
			 * @param    {[stong]}       answer      [选择题的选项]
			 * @param    {[stong]}       type        [1. 单选题， 2.多选， 3.其他]
			 * @return   {[type]}                             [description]
			 */
			// $event, list, index, key , item,
			selectAnswerChange( selected ,index,  item, name, type ){
// console.log(selected ,index,  item, name, type )
				switch(type){
					case 1:/*多选题*/
						item.html_default = true;
						item.answer = selected
						if (item.next) {
							this.Tocontone(item, index)
						}
						
					break;
					case 2:/*多选题*/

						if( is_empty(this.answerList[index].answer) ){
							this.answerList[index].answer = [];
						}
						if( selected ){
							if( !this.answerList[index].answer.includes( name) ){
								this.answerList[index].answer.push( name);
							}
						}else{
							if(this.answerList[index].answer.includes( name) ){
								this.answerList[index].answer.splice( this.answerList[index].answer.indexOf(name) , 1);
							}
						}
						/*ABCD排序*/
						this.answerList[index].answer.sort(function(a, b) {
							return a.localeCompare(b)
						})

						if (this.answerList[index].answer.length === 0) {
							item.html_default = false;
						}else{
							item.html_default = true;
						}

						item.answer = this.answerList[index].answer


						
					break;
					case 3:/*填空题*/

					if (!is_empty(name)) {
						item.html_default = true;
					}else{
						item.html_default = false;
					}
					item.answer = selected
					break;
					case 9:/*判断题*/

						item.html_default = true;
						item.answer = selected
						if (item.next) {
							this.Tocontone(item, index)
						}
					break;
					case 0:/*其他*/
						
						if (!is_empty(selected)) {
							item.html_default = true;
							this.answerList[index].answer = selected
						}else{
							item.html_default = false;
							this.answerList[index].answer = ''
						}
						item.answer = selected
						// console.log(this.answe rList)
					break;
				}
				
			},
			/**
			 * 重新排序试卷
			 * @DateTime 2019-08-12T09:38:37+0800
			 * @param    {[type]}                 arr   [description]
			 * @return   {[type]}                       [description]
			 */
			 reSort(arr){

			 	return function(a,b){
			 		var value1 = a[arr];
			 		var value2 = b[arr];
			 		return value1 - value2;
			 	}
			 },
			/**
			 * 根据参数请求试卷详情
			 * @DateTime 2019-07-22T17:37:30+0800
			 * @return   {[type]}                 [description]
			 */
			getTestList(){
				let success = (res=>{
					this.testList = res.data.test_detail;
					let data = res.data.test_detail;
					this.testObj.score  = 0

					// 计算试卷的总分数
					for (let s = 0; s < this.testList.question_type.length; s++) {
						this.testObj.score  += parseInt(this.testList.question_type[s].score)
					};


					/*根据 id 升序排序试卷*/
					// this.testList.question_list = this.testList.question_list.sort(this.reSort('qt_id'));
					this.unlimited =  res.data.is_unlimited /*否为1   为1 则不用倒计时*/
					this.totalTime =  res.data.length;
					this.recordId = res.data.task_record.id;
					this.testObj.time = res.data.time_long


					if (this.unlimited == 0) {
						this.countdowm(this.testObj.time)
					}

					
					
	
					this.testObj.name = res.data.test_detail.name;
					
					// this.testObj.time = new Date(res.data.time_long2).getTime()
			
					/*this.$nextTick(()=>{
						//改变试题 img 的 url
						let imgArr = document.querySelectorAll('.preview-conten-subject-c img')
						let baseUrl = sessionStorage.getItem('host_addr');
						for (var i = 0; i < imgArr.length; i++) {
							let _temp = imgArr[i].src
							imgArr[i].src = _temp.replace(location.protocol+'//'+location.host, baseUrl);
						}
					})*/

					/*组装一个新的试卷数据*/
					this.questionList = [];
					data.question_type.forEach((item)=>{
					
						this.questionList.push({
							id: item.id,
							count: item.count,
							name: item.question_type,
							score: item.score,
							type: item.cn_num,
							children: []
						});
					})

					
					data.question_list.forEach((list, key)=>{

						this.$set(Object.assign( list, key, {next: false}))

						if (res.data.task_record.task_record_detail.length > 0) {
							res.data.task_record.task_record_detail.forEach((record)=>{
								if (list.id == record.question_id) {
									list.studentAnswer = record
								}
							})

						}

						

						if (list.type_base_id != 1 || list.type_base_id != 2 || list.type_base_id != 4) {
							// list.answer = ''
						}

						if (list.type_base_id == 3) {

								let count = 0;
								let answerArr = []
								for (var i = 0; i < list.blank_num; i++) {
						
									answerArr.push({'answer': ''})
								}
								list.answerArr = [];
								this.$set(Object.assign( list.answerArr,  answerArr))
								// count++;
						}
					
						this.questionList.forEach((item, index)=>{
							if (list.qt_id == item.id) {
								item.children.push(list)
							}

							/*判断是否进行过答题并提交*/
							if (list.studentAnswer) {
								item.children.forEach(state=>{

									if (list.id == state.studentAnswer.question_id ) {
										/*根据选择题是否有答案，有则改变状态*/
										if (state.studentAnswer.qt_base_id == 1 || state.studentAnswer.qt_base_id == 2 || state.studentAnswer.qt_base_id == 4) {
											if (state.studentAnswer.answer != 'null' ) {
												state.html_default = true
											} 
												
										}else{/*根据非主观题是否有答案，有则改变状态*/
											if (JSON.parse(state.studentAnswer.answer) != "") {
												state.html_default = true
											}
										}
									}
								})
							}
						});

						
						/*把试题答案提出，放进一个新数组*/

						if (list.type_base_id == 1 || list.type_base_id == 2 || list.type_base_id == 4) {
							this.answerList.push({
								type: list.type_base_id,
								id: list.id,
								answer:  list.studentAnswer 
								? (JSON.parse(list.studentAnswer.answer) != null ? JSON.parse(list.studentAnswer.answer) : [] )  
								: []
							})
						}else if(list.type_base_id == 3){
							

							/*判断试卷是否提交保存过，并是否填写了答案 */
							if ( list.studentAnswer && JSON.parse(list.studentAnswer.answer) != "") {

								this.answerList.push({
									type: list.type_base_id,
									id: list.id,
									answer:  list.studentAnswer ? JSON.parse(list.studentAnswer.answer) : ''
								})

							}else{

								this.answerList.push({
									type: list.type_base_id,
									id: list.id,
									answer:  list.answerArr
								})
							}
							
							
						}else{

							this.answerList.push({
								type: list.type_base_id,
								id: list.id,
								answer:  list.studentAnswer ? JSON.parse(list.studentAnswer.answer) : ''
							})
						}

					});

					this.loading = false;
				});

				let params = {
					userid: this.$g.user_id,
					task_id: this.$route.query.id,
					type: '1,2,3'
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/task/resource_by_taskid',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			},
			/**
			 * 试卷提交数据
			 * @DateTime 2019-08-22T16:34:15+0800
			 * @return   {[type]}                 [description]
			 */
			submitTest(number){
				if (this.answerStatus == 1) {return this.$message.error('你已经提交了试卷，不能重复提交');}

				let success = (res=>{
					this.$message.success(res.msg);
					clearInterval(this.Usedtimer);

					

					if (number == 1) {
						this.$confirm('试卷批改中，请稍后...', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'success',
							customClass: 'confirm-them66',
						}).then(() => {

						}).catch(() => {});

						setTimeout( () => {
							this.$router.push({path: '/exercises/task-result', query: {id: this.$route.query.id}})
						}, 1000);
					}else{
						this.$router.push({path: '/exercises/task'})
					}
				});



				let params = {
					task_record_id: this.recordId,
					answer: this.answerList,
					falg: number/*1,提交，0保存*/
				};

				this.$ajax.post('api/task/save_answer_task_detail',params,{func: {success: success}})
			},
			/**
			 * 发布任务表单
			 * @return {[type]} [description]
			 */
			setSubmit(type){

				/*检查用户的试题是否全部完成，给出不同的文字提示*/
				let [txt, stutas] = ['', 'success']
				let testid = ''
				let cancelTXT = ''

				// for (let i = 0; i < this.questionList.length; i++) {
				// 	if (this.questionList[i].id == 3 ) {
				
				// 		for (let j = 0; j < this.questionList[i].children.length; j++) {
				// 			let item = this.questionList[i].children[j]

				// 			for (let k = 0; k < item.answerArr.length; k++) {
								
				// 				for (let a = 0; a < this.answerList.length; a++) {

				// 					if (this.answerList[a].id == item.id ) {
										
				// 						this.answerList[a].answer = item.answerArr
				// 					}
									
				// 				}
				// 			}
							
				// 		}
				// 	}
				// }

				/*检查试题是否有没有作答*/
				for (let i = 0; i < this.answerList.length; i++) {

					if (stutas =='error') {
						break;
					}

					/*填空题是多个答案*/
					if (this.answerList[i].type == 3) {
						
						let cont = []
						for (let j = 0; j < this.answerList[i].answer.length; j++) {
							if ( this.answerList[i].answer[j].answer == '') {
								txt = '还有题目未回答，是否提交试卷?'
								stutas = 'error'
								cancelTXT = '回答'
								testid = this.answerList[i].id
								break;
							}else{

								txt = '是否交试卷？';
								stutas = 'success'
								cancelTXT = '取消'
							}

						}
					}else{
						if (this.answerList[i].answer.length == 0 ) {
							txt = '还有题目未回答，是否提交试卷?'
							stutas = 'error'
							testid = this.answerList[i].id
							cancelTXT = '回答'
							break;
						}else{
							txt = '是否交试卷？';
							stutas = 'success'
							cancelTXT = '取消'
						}
					}
				}

				/*type,1 手动提交， 其他， 自动提交*/
				if (type == 1) {

					this.$confirm(txt, '提示', {
					   confirmButtonText: '交卷',
					   cancelButtonText: cancelTXT,
					    type: stutas,
					    customClass: 'myHomework',
					}).then(() => {

						this.submitTest(1)
					    
					}).catch(() => {

						if (cancelTXT == '回答') {
							let id = 'test'+ testid
							let test = document.getElementById(id)
							let timer = null
							test.classList.add('styleCss')
							this.$nextTick(() => {

								document.documentElement.scrollTop = test.offsetTop - 10;
							})

							setTimeout(()=>{

								test.classList.remove('styleCss')
							},1000);
						}
						
					});
				}else{

					this.submitTest(1)
				}
				
			},
			 /**
			  * 返回上一页
			  * @return {[type]} [description]
			  */
			 goBack(){

			 	this.$confirm('返回上一页，数据是否要保存?', '提示', {
			 		closeOnClickModal: false,
			 		distinguishCancelAndClose: true,
			 		confirmButtonText: '保存做题数据',
			 		cancelButtonText: '不保存返回',
			 		type: 'warning',
			 		customClass: 'confirm-them',
			 	}).then(() => {
			 		this.submitTest(0)

			 	}).catch((action ) => {

			 		if (action === 'cancel') {
			 			this.$router.push('/exercises/task')
			 		}
			 		
			 	});

			 },
			/**val 参数是选中的试题题目
			 * 点击选中的试题题目
			 */
			setCheck(val){
				console.log(val)
			}
		}
	}
</script>
